package com.ha7419x.controller;

import com.commons.config.MyLoadBalanceConfig;
import com.ha7419x.vo.Dept;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.netflix.ribbon.RibbonClient;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.URI;
import java.util.List;

@RestController
@RibbonClient(name = "demo-provider-dept", configuration = MyLoadBalanceConfig.class)
public class ConsumerDeptController {
    private static final String DEPT_REST_TOPIC = "demo-provider-dept";
    @Resource
    private RestTemplate restTemplate;
    @Resource
    private HttpHeaders httpHeaders;
    @Resource
    private LoadBalancerClient loadBalancerClient;

    @RequestMapping(value = "consumer/dept/get/{id}", method = RequestMethod.GET)
    public Object getDept(@PathVariable("id") Long id){
        ServiceInstance serviceInstance = this.loadBalancerClient.choose(DEPT_REST_TOPIC);
        System.out.println(
                "【*** serviceInstance ***】 host = " + serviceInstance.getHost()
                    + "、port = " + serviceInstance.getPort()
                    + "、serviceId = " + serviceInstance.getServiceId()
                    + "、uri = " + serviceInstance.getUri());
        URI deptUri = URI.create(String.format("http://%s:%s/dept/get/" + id, serviceInstance.getHost(), serviceInstance.getPort()));
        Dept dept = this.restTemplate.exchange(deptUri, HttpMethod.GET
                , new HttpEntity<>(this.httpHeaders), Dept.class).getBody();
        return dept;
    }

}
